from google.appengine.api import users
from google.appengine.ext import webapp

from base_page import BaseHandler
from data import Request

class CreateRequestHandler(BaseHandler):
  # Set authenticating logic in the following two functions.
  def CanEdit(self, user, req):
    if user.is_sys_admin or user.is_request_mod:
      return True
    if req == None:
      # TODO: everyone (with profiles) can add a new request
      return True
    if req.creator.key() == user.key():
      # One can always edit its own request
      return True
    else:
      return False

  def CanApprove(self, user, req):
    return user.is_sys_admin or user.is_donor_mod

  def ProcessGet(self):
    self.Setup('create_request.html', required_registered=True)
    req = self.GetEntityByKeyName('qid')

    # Check priviledges
    if self.CanEdit(self.user, req):
      self.template_values['can_edit'] = '1'
    else:
      # require at least editing priviledge to view this page
      self.RedirectAndRaise('/')
    if self.CanApprove(self.user, req):
      self.template_values['can_approve'] = '1'
    else:
      self.template_values['can_approve'] = '0'

    if req != None:  # edit an existing request
      self.template_values['req'] = req
      self.template_values['post_action'] = 'Action.edit'
    else:
      self.template_values['post_action'] = 'Action.add'
    self.Render()

  def ProcessPost(self):
    self.Setup('create_request.html')
    if self.post_action == 'Action.add':
      self.HandleAdd()
    elif self.post_action == 'Action.edit':
      self.HandleEdit()
    elif self.post_action == 'Action.delete':
      self.HandleDelete()
    elif self.post_action == 'Action.approve':
      self.HandleApprove()
    else:  # default handler
      self.JsonErrorReturn('Unknown action.')

  # Fill the request data from the form input
  def PopulateRequest(self, req):
    req.item_name = self.request.get('item_name')
    req.item_description = self.request.get('item_description')
    req.estimated_price = int(self.request.get('cost'))
    req.source = self.request.get('source')
    # todo: deadline_date = db.DateProperty()
    req.location = self.request.get('location')
    req.contact_info = self.request.get('contact')
    
  def HandleAdd(self):
    # Authenticate
    if not self.CanEdit(self.user, None):
      # TODO: more friendly alert
      self.RedirectLogin()

    req = Request()
    req.creator = self.user
    req.state = Request.PENDING
    self.PopulateRequest(req)
    req.put()
    # Redirect to view request page
    self.RedirectAndRaise('viewrequest?qid=%s' % req.key())

  def HandleEdit(self):
    req = self.GetEntityByKeyName('qid')
    if req == None:
      # TODO: more friendly alert
      self.RedirectAndRaise('/')

    if not self.CanEdit(self.user, req):
      # TODO: more friendly alert
      self.RedirectLogin()

    self.PopulateRequest(req)
    req.put()
    self.RedirectAndRaise('viewrequest?qid=%s' % req.key())

  def HandleDelete(self):
    req = self.GetEntityByKeyName('qid')
    if req == None:
      # TODO: more friendly alert
      self.RedirectAndRaise('/')

    if not self.CanEdit(self.user, req):
      # TODO: more friendly alert
      self.RedirectLogin()

    # TODO: delete related pledges and orders
    req.delete()
    self.RedirectAndRaise('/')

  def HandleApprove(self):
    req = self.GetEntityByKeyName('qid')
    if req == None:
      self.JsonErrorReturn('Request does not exist.')

    # Authenticate
    if not self.CanApprove(self.user, req):
      self.JsonErrorReturn('Please login as admin or moderator.')

    new_state = self.request.get('state')
    req.state = int(new_state)
    req.put()

    repsonse = {}
    repsonse['status'] = 'OK'
    repsonse['state'] = new_state
    self.JsonReturn(repsonse)
